﻿using Microsoft.Extensions.DependencyInjection;
using Modules.FaceScan.Entitys;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;

namespace Modules.FaceScan.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class FacePhotoRepository : Repository<FacePhoto, DefaultDbContext>
    {
        public FacePhotoRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
        }

        public FacePhoto? GetPersonFaceByIdCard(string idCard)
        {
            Sql sql = Sql.Builder.Select("id").From("person_face").Where("id_card=@0", idCard);
            var id = DbContext.FirstOrDefault<string>(sql);
            if (string.IsNullOrEmpty(id))
                return null;
            return Get(id);
        }

        public bool ExistsByIdCard(FacePhoto entity, string? id)
        {
            if (string.IsNullOrEmpty(entity.IdCard))
                return false;
            if (string.IsNullOrEmpty(id))
                return DbContext.Exists<FacePhoto>("id_card=@0", entity.IdCard);
            else return DbContext.Exists<FacePhoto>("id_card=@0 AND id!=@1", entity.IdCard, id);
        }

        public IEnumerable<FacePhoto> GetPersonFacesByIdCards(IEnumerable<string> idCards)
        {
            if (idCards == null || idCards.Count() == 0)
                return Enumerable.Empty<FacePhoto>();

            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("person_face")
                .Where("id_card IN(@0)", idCards);
            var ids = DbContext.FetchFirstColumn<string>(sql);
            return PopulateEntitiesByEntityIds(ids);
        }
    }
}